#!/usr/bin/env python
from astropy.table import Table
from glob import glob
import numpy as np
import sys

h1_d = sys.argv[1]
h1_idx = int(sys.argv[2])
h1_tab = Table.read(h1_d+"/mtf_result.tab",format='ipac')
mtf_h1_low = h1_tab['h_mtf'][h1_idx]
mtf_h1_high = (1-h1_tab['h_degrad'][h1_idx]/100)*mtf_h1_low

h2_d = sys.argv[3]
h2_idx = int(sys.argv[4])
h2_tab = Table.read(h2_d+"/mtf_result.tab",format='ipac')
mtf_h2_low = h2_tab['h_mtf'][h2_idx]
mtf_h2_high = (1-h2_tab['h_degrad'][h2_idx]/100)*mtf_h2_low

v1_d = sys.argv[5]
v1_idx = int(sys.argv[6])
v1_tab = Table.read(v1_d+"/mtf_result.tab",format='ipac')
mtf_v1_low = v1_tab['v_mtf'][v1_idx]
mtf_v1_high = (1-v1_tab['v_degrad'][v1_idx]/100)*mtf_v1_low

v2_d = sys.argv[7]
v2_idx = int(sys.argv[8])
v2_tab = Table.read(v2_d+"/mtf_result.tab",format='ipac')
mtf_v2_low = v2_tab['v_mtf'][v2_idx]
mtf_v2_high = (1-v2_tab['v_degrad'][v2_idx]/100)*mtf_v2_low

tab = Table()
tab['pos'] = ['1','2','mean','worst']
tab['mtf_h'] = [mtf_h1_low,mtf_h2_low,(mtf_h1_low+mtf_h2_low)/2,min(mtf_h1_low,mtf_h2_low)]
tab['mtf_v'] = [mtf_v1_low,mtf_v2_low,(mtf_v1_low+mtf_v2_low)/2,min(mtf_v1_low,mtf_v2_low)]

inhomo1 = (1-min(mtf_h1_low,mtf_v1_low)/max(mtf_h1_low,mtf_v1_low))*100
inhomo2 = (1-min(mtf_h2_low,mtf_v2_low)/max(mtf_h2_low,mtf_v2_low))*100
tab['inhomo'] = np.array([inhomo1,inhomo2,(inhomo1+inhomo2)/2,max([inhomo1,inhomo2])])

degrad1 = (1-min(mtf_h1_low,mtf_h2_low)/max(mtf_h1_low,mtf_h2_low))*100
degrad2 = (1-min(mtf_v1_low,mtf_v2_low)/max(mtf_v1_low,mtf_v2_low))*100
tab['degrad'] = np.array([degrad1,degrad2,(degrad1+degrad2)/2,max(degrad1,degrad2)])

tab.write("mtf_final_result.tab",format='ipac',overwrite=True)
